﻿#region File and License Information
/*
<File>
	<Copyright>Copyright © 2010, Daniel Vaughan. All rights reserved.</Copyright>
	<License>
		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY
		EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="dbvaughan@gmail.com"/>
	<CreationDate>2010-03-21 18:52:08Z</CreationDate>
</File>
*/
#endregion

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

using DanielVaughan.Sokoban.Commands;

using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;

namespace DanielVaughan.Sokoban.UI
{
	public partial class MainPage
	{
		readonly SoundEffect footStepSoundEffect = SoundEffect.FromStream(TitleContainer.OpenStream("Audio/Footstep.wav"));
		readonly SoundEffect introSoundEffect = SoundEffect.FromStream(TitleContainer.OpenStream("Audio/Intro.wav"));
		readonly SoundEffect treasurePushSoundEffect = SoundEffect.FromStream(TitleContainer.OpenStream("Audio/TreasurePush.wav"));
		readonly SoundEffect dingDongSoundEffect = SoundEffect.FromStream(TitleContainer.OpenStream("Audio/DingDong.wav"));
		readonly SoundEffect applauseSoundEffect = SoundEffect.FromStream(TitleContainer.OpenStream("Audio/DullClapping.wav"));
		readonly SoundEffect levelCompleteSoundEffect = SoundEffect.FromStream(TitleContainer.OpenStream("Audio/Movement_from_NEO_Sounds.wav"));

		public MainPage()
		{
			InitializeComponent();
			DataContext = new Game(new SokobanService());
			Loaded += OnLoaded;
		}

		Game Game
		{
			[DebuggerStepThrough]
			get
			{
				return (Game)DataContext;
			}
		}

		#region PageOrientation Dependency Property

		public static DependencyProperty PageOrientationProperty = DependencyProperty.Register(
			"PageOrientation", typeof(PageOrientation), typeof(MainPage), new PropertyMetadata(PageOrientation.None));

		[Description("PropertyDescription")]
		public PageOrientation PageOrientation
		{
			get
			{
				return (PageOrientation)GetValue(PageOrientationProperty);
			}
			set
			{
				SetValue(PageOrientationProperty, value);
			}
		}

		#endregion
		
		readonly CommandManager commandManager = new CommandManager();
		GameState gameState = GameState.Loading;

		/// <summary>
		/// Gets or sets a value indicating whether the press any key
		/// message is displayed.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if the press any key message is displayed; 
		/// otherwise, <c>false</c>.
		/// </value>
		bool ContinuePromptVisible
		{
			get
			{
				return textBlock_PressAnyKey.Visibility == Visibility.Visible;
			}
			set
			{
				textBlock_PressAnyKey.Visibility = value ? Visibility.Visible : Visibility.Collapsed;
			}
		}

		bool loaded;

		void OnLoaded(object sender, RoutedEventArgs e)
		{
			// Required to initialize variables
			InitializeComponent();

			if (loaded)
			{
				return;
			}
			loaded = true;

			/* Set the feedback message to empty. */
			feedbackControl.Text = string.Empty;
			/* Hide the press any key textblock. */
			ContinuePromptVisible = false;

			/* Begin listening for game events. */
			Game.PropertyChanged += game_PropertyChanged;

			try
			{
				/* Load and start the first level of the game. */
				Game.Start();
			}
			catch (Exception ex)
			{
				/* Handle this. */
				Console.WriteLine(ex.StackTrace);
				throw;
			}
			/* Ready to listen for keyboard events. */
			KeyDown += Page_KeyDown;

			OrientationChanged += delegate
			                      	{
										PageOrientation = Orientation;
			                      		RefreshGameGrid();
			                      	};
			SizeChanged += delegate { RefreshGameGrid(); };
			PageOrientation = Orientation;
		}

		void RefreshGameGrid()
		{
			var width = CalculateCellSize();

			foreach (var columnDefinition in grid_Game.ColumnDefinitions)
			{
				columnDefinition.MaxWidth = columnDefinition.MinWidth = width;
			}

			foreach (var rowDefinition in grid_Game.RowDefinitions)
			{
				rowDefinition.MaxHeight = rowDefinition.MinHeight = width;
			}

			foreach (var c in cellControls)
			{
				c.MaxWidth = c.MaxHeight = width;
				c.UpdateDimensions();
			}
		}

		void PlayAudioClip(SoundEffect soundEffect)
		{
		    FrameworkDispatcher.Update();
            soundEffect.Play();
		}

		static bool ShiftPressed
		{
			get
			{
				return (Keyboard.Modifiers & ModifierKeys.Shift) != 0;
			}
		}

		static bool ControlPressed
		{
			get
			{
				return (Keyboard.Modifiers & ModifierKeys.Control) != 0;
			}
		}

		void game_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			switch (e.PropertyName)
			{
				case "GameState":
					UpdateGameDisplay();
					break;
			}
		}

		/// <summary>
		/// We set feedback messages and so one here,
		/// using the game's <see cref="GameState"/>.
		/// </summary>
		void UpdateGameDisplay()
		{
			switch (Game.GameState)
			{
				case GameState.Loading:
					feedbackControl.Text = "Loading...";
					ContinuePromptVisible = false;
					break;
				case GameState.GameOver:
					feedbackControl.Text = "Game Over";
					ContinuePromptVisible = true;
					break;
				case GameState.Running:
					ContinuePromptVisible = false;
					feedbackControl.Text = string.Empty;
					if (gameState == GameState.Loading)
					{
						InitialiseLevel();
					}
					break;
				case GameState.LevelCompleted:
					feedbackControl.Text = "Level Completed!";
					PlayAudioClip(levelCompleteSoundEffect);
					ContinuePromptVisible = true;
					break;
				case GameState.GameCompleted:
					feedbackControl.Text = "Congratulations. \nGame completed! " 
							+ "\nPlease let the author know by emailing \ndbvaughan \nAT gmail.com";
					PlayAudioClip(applauseSoundEffect);
					break;
			}
			gameState = Game.GameState;
		}

		readonly List<CellControl> cellControls = new List<CellControl>();

		/// <summary>
		/// Initialises the game grid using the level.
		/// </summary>
		void InitialiseLevel()
		{
			cellControls.Clear();
			commandManager.Clear();

			grid_Game.Children.Clear();
			grid_Game.RowDefinitions.Clear();
			grid_Game.ColumnDefinitions.Clear();

			for (int i = 0; i < Game.Level.RowCount; i++)
			{
				grid_Game.RowDefinitions.Add(new RowDefinition());
			}

			for (int i = 0; i < Game.Level.ColumnCount; i++)
			{
				grid_Game.ColumnDefinitions.Add(new ColumnDefinition());
			}

			var cellSize = CalculateCellSize();
			
			for (int row = 0; row < Game.Level.RowCount; row++)
			{
				for (int column = 0; column < Game.Level.ColumnCount; column++)
				{
					Cell cell = Game.Level[row, column];
					cell.PropertyChanged += cell_PropertyChanged;

					CellControl cellControl = new CellControl(cell);
					cellControl.MaxHeight = cellControl.MaxWidth = cellSize;
					cellControl.Click += Cell_Click;
                    
					Grid.SetColumn(cellControl, column);
					Grid.SetRow(cellControl, row);
					grid_Game.Children.Add(cellControl);
					cellControls.Add(cellControl);
				}
			}

			/* Play the intro audio clip. */
			PlayAudioClip(introSoundEffect);
			/* Listen for actor property changes. */
			//Game.Level.Actor.PropertyChanged += Actor_PropertyChanged;

			RefreshGameGrid();
		}

		double CalculateCellSize()
		{
			double width = ActualWidth - 10;
			double height = ActualHeight - 70;

			int columns = Game != null && Game.Level != null ? Game.Level.ColumnCount : 1;
			int rows = Game != null && Game.Level != null ? Game.Level.RowCount : 1;
			var cellWidth = width / columns;
			var cellHeight = height / rows;
			var result = Math.Min(cellWidth, cellHeight);
			return result;
		}

		void Cell_Click(object sender, RoutedEventArgs e)
		{
			/* When the user clicks a cell, we want to 
			 have the actor move there. */
			var cellControl = (CellControl)sender;
			Cell cell = cellControl.Cell;
			CommandBase command;

			if (ShiftPressed)
			{
				command = new PushCommand(Game.Level, cell.Location);
			}
			else
			{
				command = new JumpCommand(Game.Level, cell.Location);
			}
			commandManager.Execute(command);
		}

		void cell_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			Cell cell = (Cell)sender;
			if (e.PropertyName == "CellContents")
			{	/* Play an audio clip depending on the state of the cell. */
				if (cell.CellContents is Actor)
				{
					PlayAudioClip(footStepSoundEffect);
				}
				else if (cell.CellContents is Treasure)
				{
					if (cell is GoalCell)
					{
						PlayAudioClip(dingDongSoundEffect);
					}
					else
					{
						PlayAudioClip(treasurePushSoundEffect);
					}
				}
			}
		}

		protected void PlayControl_RestartLevel(object sender, EventArgs e)
		{
			Game.RestartLevel();
		}

		#region Level Code

		void Button_RestartLevel_Click(object sender, RoutedEventArgs e)
		{
			Game.RestartLevel();
		}

		void TextBox_LevelCode_GotFocus(object sender, RoutedEventArgs e)
		{
			textBox_LevelCode.Text = string.Empty;
			textBox_LevelCode.Opacity = 100;
		}

		void TextBox_LevelCode_LostFocus(object sender, RoutedEventArgs e)
		{
			if (!Game.TryGotoToLevel(textBox_LevelCode.Text))
			{
				textBox_LevelCode.Text = Game.LevelCode;
			}
			textBox_LevelCode.Opacity = 40;
		}

		void TextBox_LevelCode_KeyUp(object sender, KeyEventArgs e)
		{
			if (e.Key != Key.Enter)
			{
				return;
			}
			if (!Game.TryGotoToLevel(textBox_LevelCode.Text))
			{
				textBox_LevelCode.Text = Game.LevelCode;
			}
		}
		#endregion

		void Button_Undo_Click(object sender, RoutedEventArgs routedEventArgs)
		{
			commandManager.Undo();
		}

		void Button_Redo_Click(object sender, RoutedEventArgs routedEventArgs)
		{
			commandManager.Redo();
		}

		void Button_Continue_Click(object sender, RoutedEventArgs e)
		{
			feedbackControl.Visibility = Visibility.Collapsed;
			Game.GotoNextLevel();
		}

		void Page_KeyDown(object sender, KeyEventArgs e)
		{
			if (sender == textBox_LevelCode)
			{
				return;
			}

			CommandBase command = null;
			Level level = Game.Level;
			Key key = e.Key;
			if (Game != null)
			{
				if (Game.GameState == GameState.Running)
				{
					switch (key)
					{
						case Key.I:
							command = new MoveCommand(level, Direction.Up);
							break;
						case Key.K:
							command = new MoveCommand(level, Direction.Down);
							break;
						case Key.J:
							command = new MoveCommand(level, Direction.Left);
							break;
						case Key.L:
							command = new MoveCommand(level, Direction.Right);
							break;
						case Key.Z:
							if (ShiftPressed)
							{
								commandManager.Undo();
							}
							break;
						case Key.Y:
							if (ControlPressed)
							{
								commandManager.Redo();
							}
							break;
					}
				}
				else
				{
					switch (Game.GameState)
					{
						case GameState.GameOver:
							Game.Start();
							break;
						case GameState.LevelCompleted:
							Game.GotoNextLevel();
							break;
					}
				}
			}

			if (command != null)
			{
				commandManager.Execute(command);
			}
		}
	}
}
